<?php
/* ******************************************************** */
/* Arcans Project (2010)                                    */
/* Jeu 3D en temps réel par navigateur, conception et       */
/* Développement dans la notice                             */
/* Jeu sous licence GNU GPL v3 (voir NOTICE et COPYING)     */
/* ******************************************************** */

//**********************
//classe de réponse ajax
//**********************
class AjaxReponseClass {
	//constructeur :
	public static function initAjaxFun($address,$seek) {
		switch ($address) {
			case "ains" : AjaxReponseClass::ainsFun(1,$seek); break;
			case "ains2" : AjaxReponseClass::ainsFun(2,$seek); break;
			case "acon" : AjaxReponseClass::connexFun(); break;
			case "adecon" : AjaxReponseClass::decoFun(); break;
			case "afpwd" : AjaxReponseClass::fpwdFun($seek); break;
			case "aerrmail" : AjaxReponseClass::errmailFun($seek); break;
			case "asupp" : AjaxReponseClass::suppFun($seek); break;
			case "amodcp" : AjaxReponseClass::mod_cpFun($seek); break;
			case "acntt" : AjaxReponseClass::cnttFun($seek); break;
			case "apanc" : AjaxReponseClass::pancFun(); break;
			case "acanc" : AjaxReponseClass::cancFun(); break;
			case "amesschat" : AjaxReponseClass::messChatFun(); break;
			case "amajchat" : AjaxReponseClass::majchatFun(); break;
			case "aimail" : AjaxReponseClass::imailFun(); break;
		}
	}
	//constantes :
	const regval = '/^[\w]+[\w\-\.]{2,}$/';
	const regemail = '/^[a-zA-Z0-9]+([_|\.|-]{1}[a-zA-Z0-9]+)*@[a-zA-Z0-9]+([_|\.|-]­{1}[a-zA-Z0-9]+)*[\.]{1}[a-z]{2,6}$/';
	//méthodes :
	//gestion de l'inscription
	private static function ainsFun($level,$seek) {
		$infos["pseudo"] = htmlentities($_POST["info0"]);
		$mysqlins = new MysqlClass(0);
		if (preg_match(self::regval, $infos["pseudo"])) {
			$result = $mysqlins->resultFun("count", "users", "users='".$infos["pseudo"]."'");
			$result = $result + $mysqlins->resultFun("count", "unvalid_users", "users='".$infos["pseudo"]."'");
			if ($level == 2 && $result == 0) {
				$infos["email"] = htmlentities($_POST["info1"]);
				if (preg_match(self::regemail, $infos["email"])) {
					//création du mot de passe :
					$pwd_tab_alp = array ("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","0","1","2","3","4","5","6","7","8","9");
					$pwd_tab = array_rand($pwd_tab_alp, 8);
					$pwd = "";
					foreach ($pwd_tab as $elt) $pwd .= $pwd_tab_alp[$elt];
					//création du code :
					$code = hash("sha256", mt_rand());
					//enregistrement dans la base de données :
					$values = "values('".$infos["pseudo"]."', '".$pwd."', '".$infos["email"]."', '".$code."')";
					$mysqlins2 = new MysqlClass(1);
					$mysqlins2->resultFun("insert", "unvalid_users", "(users,password,email,code) ".$values);
					//envoi email
					$element = array ("ains2",$infos["pseudo"],$pwd,$code);
					mailSend($infos["email"],"Arcans Project : inscription",$element,$seek);
					AjaxReponseClass::sortieFun('text',0);
				}
				else AjaxReponseClass::sortieFun('text',3);
			}
			elseif ($result == 0) AjaxReponseClass::sortieFun('text',0);
			else AjaxReponseClass::sortieFun('text',1);
		}
		else AjaxReponseClass::sortieFun('text',2);
	}
	//gestion de la connexion
	private static function connexFun() {
		$tentatives = 0;
		$addr_ip = md5($_SERVER["REMOTE_ADDR"]);
		$mysql_ip = new MysqlClass(0);
		$res_ip = $mysql_ip->resultFun("count", "blacklist", "addr_ip='".$addr_ip."'");
		if ($res_ip == 1) {
			$res_ip = $mysql_ip->resultFun("select", "blacklist", "addr_ip='".$addr_ip."'");
			$tentatives = $res_ip["tentatives"];
		}
		if ($tentatives < 10) {
			$infos["pseudo"] = htmlentities($_POST["info0"]);
			$infos["pwd"] = htmlentities($_POST["info1"]);
			if (preg_match(self::regval, $infos["pseudo"]) && preg_match(self::regval, $infos["pwd"])) {
				$mysqlcon = new MysqlClass(0);
				$result = $mysqlcon->resultFun("count", "users", "users='".$infos["pseudo"]."'");
				if ($result) {
					$hash = md5(hash("sha256", $infos["pseudo"]) . $infos["pwd"]);
					$result = $mysqlcon->resultFun("count", "users", "users='".$infos["pseudo"]."' and password='".$hash."'");
					if ($result == 1) {
						$result = $mysqlcon->resultFun("select", "users", "password='".$hash."'");
						$_SESSION["pseudo"] = $infos["pseudo"];
						$_SESSION["id"] = $result["id"];
						$_SESSION["level"] = $result["level"];
						$_SESSION["panel"] = 1;
						$_SESSION["canal"] = 1;
						//nettoyage de unvalid_users
						$mysqlclean = new MysqlClass(2);
						$date = date("Y-m-d H:i:s",time() - (7*24*60*60));
						$mysqlclean->resultFun("delete", "unvalid_users", "time<'".$date."'");
						//nettoyage de blacklist
						$date = date("Y-m-d H:i:s",time() - (24*60*60));
						$mysqlclean->resultFun("update", "blacklist", "tentatives=0 where addr_ip='".$addr_ip."'");
						//fin de la connexion
						AjaxReponseClass::sortieFun('text',1);
					}
					else {
						$mysql_hack = new MysqlClass(2);
						if ($tentatives > 0) $mysql_hack->resultFun("update", "blacklist", "tentatives='". ($tentatives + 1)."' where addr_ip='".$addr_ip."'");
						else $mysql_hack->resultFun("insert", "blacklist", "(addr_ip,tentatives) values('".$addr_ip."',1)");
						AjaxReponseClass::sortieFun('text',0);
					}
				}
				else {
					$mysql_hack = new MysqlClass(2);
					if ($tentatives > 0) $mysql_hack->resultFun("update", "blacklist", "tentatives='".($tentatives + 1)."' where addr_ip='".$addr_ip."'");
					else $mysql_hack->resultFun("insert", "blacklist", "(addr_ip,tentatives) values('".$addr_ip."',1)");
					AjaxReponseClass::sortieFun('text',2);
				}
			}
			else AjaxReponseClass::sortieFun('text',3);
		}
		else AjaxReponseClass::sortieFun('text',4);
	}
	//gestion de la déconnexion
	private static function decoFun() { $_SESSION = array(); session_destroy(); break; }
	//gestion de l'oubli du mot de passe
	private static function fpwdFun($seek) {
		$infos["pseudo"] = htmlentities($_POST["info0"]);
		$infos["email"] = htmlentities($_POST["info1"]);
		if (preg_match(self::regval, $infos["pseudo"])) {
			if (preg_match(self::regemail, $infos["email"])) {
				$mysqlfpwd = new MysqlClass(0);
				$result = $mysqlfpwd->resultFun("count", "users", "users='".$infos["pseudo"]."' and email='".$infos["email"]."'");
				if ($result == 1) {
					//modification de la base de données
					$pwd_tab_alp = array ("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","0","1","2","3","4","5","6","7","8","9");
					$pwd_tab = array_rand($pwd_tab_alp, 8);
					$pwd = "";
					foreach ($pwd_tab as $elt) $pwd .= $pwd_tab_alp[$elt];
					$code = md5(hash("sha256", $infos["pseudo"]) . hash("sha256", $pwd));
					$mysqlfpwdmod = new MysqlClass(2);
					$mysqlfpwdmod->resultFun("update", "users", "password='".$code."' where users='".$infos["pseudo"]."'");
					//envoi du mail
					mailSend($infos["email"],"Arcans Project : oubli du mot de passe",array ("fpwd",$infos["pseudo"],$pwd),$seek);
					//fin de la requete
					AjaxReponseClass::sortieFun('text',$result);
				}
				else AjaxReponseClass::sortieFun('text',0);
			}
			else AjaxReponseClass::sortieFun('text',3);
		}
		else AjaxReponseClass::sortieFun('text',2);
	}
	//gestion du renvoi du mail d'inscription
	private static function errmailFun($seek) {
		$infos["pseudo"] = htmlentities($_POST["info0"]);
		$infos["email"] = htmlentities($_POST["info1"]);
		if (preg_match(self::regval, $infos["pseudo"])) {
			if (preg_match(self::regemail, $infos["email"])) {
				$mysqlerrm = new MysqlClass(0);
				$result = $mysqlerrm->resultFun("count", "unvalid_users", "users='".$infos["pseudo"]."'");
				if ($result == 1) {
					$result = $mysqlerrm->resultFun("count", "unvalid_users", "users='".$infos["pseudo"]."' and email='".$infos["email"]."'");
					if ($result == 1) {
						//création du nouveau mot de passe et du nouveau code
						$pwd_tab_alp = array ("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","0","1","2","3","4","5","6","7","8","9");
						$pwd_tab = array_rand($pwd_tab_alp, 8);
						$pwd = "";
						foreach ($pwd_tab as $elt) $pwd .= $pwd_tab_alp[$elt];
						$code = hash("sha256", mt_rand());
						//enregistrement dans la base de données
						$mysqlerrmW = new MysqlClass(2);
						$mysqlerrmW->resultFun("update", "unvalid_users", "password='".$pwd."', code='".$code."', time=current_timestamp where users='".$infos["pseudo"]."'");
						//envoi du mail
						$element = array ("renvoi_ins",$infos["pseudo"],$pwd,$code);
						mailSend($infos["email"],"Arcans Project : inscription, renvoi",$element,$seek);
						//fin de la requête ajax, envoi de la réponse
						AjaxReponseClass::sortieFun('text',1);
					}
					else AjaxReponseClass::sortieFun('text',0);
				}
				else {
					$result = $mysqlerrm->resultFun("count", "users", "users='".$infos["pseudo"]."'");
					if ($result == 1) AjaxReponseClass::sortieFun('text',2);
					else AjaxReponseClass::sortieFun('text',5);
				}
			}
			else AjaxReponseClass::sortieFun('text',4);
		}
		else AjaxReponseClass::sortieFun('text',3);
	}
	//gestion de la suppression de compte
	private static function suppFun ($seek) {
		$infos["pseudo"] = htmlentities($_POST["info0"]);
		$infos["pwd"] = htmlentities($_POST["info1"]);
		if (preg_match(self::regval, $infos["pseudo"]) && preg_match(self::regval, $infos["pwd"])) {
			$mysqlcon = new MysqlClass(0);
			$hash = md5(hash("sha256", $infos["pseudo"]) . $infos["pwd"]);
			$result = $mysqlcon->resultFun("count", "users", "users='".$infos["pseudo"]."' and password='".$hash."'");
			if ($result == 1) {
				//récupération des données
				$code = md5(mt_rand());
				$res = $mysqlcon->resultFun("select", "users", "users='".$infos["pseudo"]."'");
				//enregistrement dans unvalid, et suppression dans users
				$mysqlsupp = new MysqlClass(2);
				$mysqlsupp->resultFun("insert", "unvalid_users", "(users,password,email,code) values('".$infos["pseudo"]."','','".$res["email"]."','".$code."')");
				$mysqlsupp->resultFun("delete",  "users", "users='".$infos["pseudo"]."'");
				//envoi du mail
				mailSend($res["email"],"Arcans Project : Suppression de compte",array("suppression",$infos["pseudo"],$code),$seek);
				//déconnexion
				$_SESSION = array();
				session_destroy();
				AjaxReponseClass::sortieFun('text',$result);
			}
			else AjaxReponseClass::sortieFun('text',$result);
		}
		else AjaxReponseClass::sortieFun('text',3);
	}
	//gestion de la modification des données du compte
	private static function mod_cpFun ($seek) {
		$infos["pseudo"] = htmlentities($_POST["info0"]);
		$infos["pwd"] = htmlentities($_POST["info1"]);
		if (preg_match(self::regval, $infos["pseudo"]) && preg_match(self::regval, $infos["pwd"])) {
			$hash = md5(hash("sha256", $infos["pseudo"]) . $infos["pwd"]);
			$mysqltest = new MysqlClass(0);
			$result = $mysqltest->resultFun("count", "users", "users='".$infos["pseudo"]."' and password='".$hash."'");
			if ($result == 1 && ($infos["pseudo"] == $_SESSION["pseudo"])) {
				$infos["pseudon"] = htmlentities($_POST["info2"]);
				$infos["emailn"] = htmlentities($_POST["info3"]);
				$infos["pwdn"] = htmlentities($_POST["info4"]);
				$change = 0;
				$test = 0;
				if ($infos["pseudon"] != "_") {
					if (preg_match(self::regval, $infos["pseudon"])) {
						$res = $mysqltest->resultFun("count", "users", "users='".$infos["pseudon"]."'");
						if ($res == 0) $res = $mysqltest->resultFun("count", "unvalid_users", "users='".$infos["pseudo"]."'");
						if ($res == 0) $change = 1;
						else $test = $test + 1;
					}
					else $test = $test + 1;
				}
				if ($infos["emailn"] != "_") {
					if (preg_match(self::regemail, $infos["emailn"])) $change = $change + 2;
					else $test = $test + 2;
				}
				if ($infos["pwdn"] != "_") {
					if (preg_match(self::regval, $infos["pwdn"])) $change = $change + 4;
					else $test = $test + 4;
				}
				if ($test == 0) {
					$modif = 0;
					$bdd = "";
					//enregistrement dans la base de données
					$mysqlinsert = new MysqlClass(2);
					switch ($change) {
						case 1 :
							$code = md5(hash("sha256", $infos["pseudon"]) . $infos["pwd"]);
							$bdd = "users='".$infos["pseudon"]."',password='".$code."'";
							$modif = $infos["pseudon"]; break;
						case 2 : $bdd = "email='".$infos["emailn"]."'"; $modif = $infos["emailn"]; break;
						case 3 :
							$code = md5(hash("sha256", $infos["pseudon"]) . $infos["pwd"]);
							$bdd = "users='".$infos["pseudon"]."',password='".$code."',email='".$infos["emailn"]."'";
							$modif = array($infos["pseudon"], $infos["emailn"]); break;
						case 4 :
							$code = md5(hash("sha256", $_SESSION["pseudo"]) . hash("sha256", $infos["pwdn"]));
							$bdd = "password='".$code."'"; $modif = $infos["pwdn"]; break;
						case 5 :
							$code = md5(hash("sha256", $infos["pseudon"]) . hash("sha256", $infos["pwdn"]));
							$bdd = "users='".$infos["pseudon"]."',password='".$code."'";
							$modif = array($infos["pseudon"], $infos["pwdn"]); break;
						case 6 :
							$code = md5(hash("sha256", $_SESSION["pseudo"]) . hash("sha256", $infos["pwdn"]));
							$bdd = "password='".$code."',email='".$infos["emailn"]."'";
							$modif = array($infos["emailn"], $infos["pwdn"]); break;
						case 7 :
							$code = md5(hash("sha256", $infos["pseudon"]) . hash("sha256", $infos["pwdn"]));
							$bdd = "users='".$infos["pseudon"]."',password='".$code."',email='".$infos["emailn"]."'";
							$modif = array($infos["pseudon"],$infos["pwdn"], $infos["emailn"]); break;
					}
					$mysqlinsert->resultFun("update", "users", $bdd." where users='".$_SESSION["pseudo"]."'");
					//mise à jour des variables de session
					$conserv = $_SESSION["pseudo"];
					if ($infos["pseudon"] != "_") $_SESSION["pseudo"] = $infos["pseudon"];
					//envoi du mail d'information
					$res = $mysqltest->resultFun("select", "users", "users='".$_SESSION["pseudo"]."'");
					mailSend($res["email"],"Arcans Project : Modification du compte",array ("modcp", $conserv, $change, $modif),$seek);
					AjaxReponseClass::sortieFun('text',10);
				}
				else AjaxReponseClass::sortieFun('text',$test);
			}
			else AjaxReponseClass::sortieFun('text',9);
		}
		else AjaxReponseClass::sortieFun('text',8);
	}
	//gestion de la page de contact
	private static function cnttFun ($seek) {
		$title = htmlentities($_POST["info0"]);
		$sender = htmlentities($_POST["info1"]);
		$texte = htmlentities($_POST["info2"]);
		mailSend("arcans.project@gmail.com","Arcans Project : message de contact",array ("contact",$title,$sender,$texte),$seek);
	}
	//gestion du panel (ouvert/fermé)
	private static function pancFun() {
		$_SESSION["panel"] = htmlentities($_POST["info0"]);
		AjaxReponseClass::sortieFun("text",0);
	}
	//gestion du canal
	private static function cancFun() {
		$_SESSION["canal"] = htmlentities($_POST["info0"]);
		$mysql_infos = new MysqlClass(0);
		$lines_fetch = $mysql_infos->resultFun("selectm", "chat", " where canal=".$_SESSION["canal"]." order by date desc limit 20");
		AjaxReponseClass::ChatFun($lines_fetch, array("new", 0));
	}
	//enregistrement des messages dans les canaux
	private static function messChatFun() {
		$texte = htmlspecialchars($_POST["info0"]);
		$id = htmlentities($_POST["info1"]);
		$mysql_envoi = new MysqlClass(2);
		$values = "values(".$_SESSION["canal"].",".$_SESSION["id"].",'classic','".$texte."')";
		$mysql_envoi->resultFun("insert", "chat", "(canal,expediteur,type,message) ".$values);
		$lines_fetch = $mysql_envoi->resultFun("selectm", "chat", " where canal=".$_SESSION["canal"]." and id > ".$id." order by date desc limit 20");
		AjaxReponseClass::chatFun($lines_fetch, array("add", "no"));
	}
	//mise à jour du chat
	private static function majchatFun() {
		$id = htmlentities($_POST["info0"]);
		$mysql_chat = new MysqlClass(0);
		$lines_fetch = $mysql_chat->resultFun("selectm", "chat", " where canal=".$_SESSION["canal"]." and id > ".$id." order by date desc limit 20");
		AjaxReponseClass::chatFun($lines_fetch, array("add", "no"));
	}
	//mise en forme des données du chat
	private static function chatFun($lines_fetch, $res_r) {
		$mysql_pseudo = new MysqlClass(0);
		$res[1] = "";
		while ($line = mysql_fetch_array($lines_fetch)) {
			$heure = date("H:i", strtotime($line["date"]));
			$pseudo = $mysql_pseudo->resultFun("select", "users", "id=".$line["expediteur"]);
			$res[1] = '<line user="'.$pseudo["users"].'" heure="'.$heure.'" id="'.$line["id"].'">'.$line["message"].'</line>'.$res[1];
		}
		if ($res[1] != "") $res[0] = $res_r[0]; else $res[0] = $res_r[1];
		AjaxReponseClass::sortieFun("xml", $res);
	}
	//mise à jour de la liste de messagerie
	private static function imailFun() {
		$mysql_list = new MysqlClass(0);
		$id_pseudo = $mysql_list->resultFun("select", "users", "users='".$_SESSION["pseudo"]."'");
		$mails = $mysql_list->resultFun("selectm", "dest_table", " where id_dest=".$id_pseudo["id"]);
		$res = array(0,"");
		while ($line = mysql_fetch_array($mails)) {
			$res[1] = "";
			//
			$res[0]++;
		}
		//
		AjaxReponseClass::sortieFun("xml", $res);
	}
	//fonction de sortie d'ajax
	private static function sortieFun($type, $resultat) {
		header('Content-Type: application/xml');
		header("Expires: Mon, 26 Jul 1997 05:00:00 Paris");
		header("Last-Modified: ".date("D, d M Y H:i:s")." Paris");
		header("Cache-Control: no-store, no-cache, must-revalidate");
		header("Cache-Control: post-check=0, pre-check=0", false);
		header("Pragma: no-cache");
		echo '<?xml version="1.0" encoding="UTF-8" ?><racine>';
		if ($type == 'text') echo '<infos type="text" value="'.$resultat.'" />';
		elseif ($type == 'xml') echo '<infos type="xml" value="'.$resultat[0].'" />'.$resultat[1];
		echo '</racine>';
	}
}
?>